<%--
  Created by IntelliJ IDEA.
  User: Gemini
  Date: 2018/7/26
  Time: 10:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../common.jsp"%>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>库位信息</title>

    <!--  提示框的样式 -->

    <%--<script src="js/toastr.options.js"></script>--%>

    <script type="text/javascript">
        $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();
            //初始化提示框的位置：top-center，bottom-left，bottom-right
            toastr.options.positionClass = 'toast-top-center';

            //模态框关闭事件
            $('#exampleModal').on('hide.bs.modal',function(){
                //表单清空
                $("#fm")[0].reset();
                $('#roleId').val("").trigger('change');
                //表单验证清空
                $('#fm').data('bootstrapValidator').resetForm(true);
            });


            //jQuery，既阻止默认行为又停止冒泡  导入按钮
            $("#ss").on('click',function(){
                return false;//当然 也阻止了事件本身
            });

            // //调用下拉框多选初始化方法
            // getPlan();

        });


        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_departments').bootstrapTable({
                    url: '${pageContext.request.contextPath }/base/location/selectBaseLocationInfo.do',         //请求后台的URL（*）
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortable: false,                     //是否启用排序
                    sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber:1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 20, 30],        //可供选择的每页的行数（*）
                    strictSearch: true,
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "positionId",                     //每一行的唯一标识，一般为主键列
                    detailView: false,                   //是否显示父子表
                    columns:  [{
                        checkbox: true
                    }, {
                        field: 'positionId',
                        title: '库位id',
                        visible: false
                    }, {
                        field: 'areanumbering',
                        title: '库位编号',
                        align:'center'
                    }, {
                        field: 'areaname',
                        title: '库位名称',
                        align:'center'
                    } , {
                        field: 'partStore.locationname',
                        title: '所属仓库',
                        align:'center'
                    } , {
                        field: 'areatype',
                        title: '库位类型',
                        align:'center'
                    }, {
                        field: 'areapeople',
                        title: '录入人',
                        align:'center'
                    }, {
                        field: 'areaptime',
                        title: '录入时间',
                        align:'center'
                    }]
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset/params.limit+1,  //页码
                    areanumbering:$.trim($('#areanumberingc').val()),
                    areastorehouse:$.trim($('#areastorehousec').val()),

                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {
            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };

            return oInit;
        };

        //刷新表格
        function refresh(){
            $("#tb_departments").bootstrapTable("refreshOptions",{pageNumber:1})
        };

        function doDelete() {
            var row=$.map($("#tb_departments").bootstrapTable('getSelections'),function(row){
                return row ;
            });
            if (row.length == 0) {
                toastr.warning('请至少选择一条数据!');
            }else{
                var ids="";
                var names="";
                for(var i=0;i<row.length;i++){
                    if(i==0 || i=="0"){
                        ids+=row[i].positionId;
                    }else{
                        ids+=","+row[i].positionId;
                    }
                }

                //询问框
                Ewin.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
                    if (!e) {
                        return;
                    }
                    var url = "${pageContext.request.contextPath }/base/location/deleteBaseLocationInfo.do";
                    $.post(url, "ids="+ids, function(data) {
                        if (data >= 1) {
                            toastr.success('删除成功');
                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                $('#tb_departments').bootstrapTable('refresh');
                                refresh()
                            },1000);
                        } else {
                            toastr.error('删除失败');
                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                $('#tb_departments').bootstrapTable('refresh');
                                refresh()
                            },1000);
                        }
                    });
                });
            }
        };

        //打开添加模态框
        function doAdd() {
            $("#bt").html("新增库位信息");
            addFig  =  false;
            $("#positionId").val("");
            $('#areastorehouse').val("").trigger('change');
            $('#exampleModal').modal(open);

        };

        //修改赋值
        function doView() {
            //取表格的选中行数据
            var row = $("#tb_departments").bootstrapTable('getSelections');
            if (row.length == 1) {
                $("#bt").html("修改库位信息");
                $("#positionId").val(row[0].positionId);
                $("#areanumbering").val(row[0].areanumbering);
                $("#areaname").val(row[0].areaname);
                $("#areatype").val(row[0].areatype);

                $('#areastorehouse').val(row[0].areastorehouse).trigger('change');

                $('#exampleModal').modal(open);
            }else{
                toastr.warning('请选择一条数据!');
            }
        };

        //保存
        addFig  =  false
        function save() {

            if(addFig == true){
                return false;
            }
            addFig  =  true;

            var bootstrapValidator = $("#fm").data('bootstrapValidator');
            //开启验证
            bootstrapValidator.validate();
            if (bootstrapValidator.isValid()){
                if (document.getElementById('positionId').value=='') {
                    var url = "${pageContext.request.contextPath }/base/location/insertBaseLocationInfo.do";
                    var title="新增";
                } else {
                    var url = "${pageContext.request.contextPath }/base/location/editBaseLocationInfo.do";
                    var title="修改";
                }
                $.post(url, $("#fm").serialize(), function(data) {
                    if (data == 1) {
                        toastr.success(title+'成功');
                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                            $('#exampleModal').modal('hide');
                            $('#tb_departments').bootstrapTable('refresh');
                            refresh();
                            addFig  =  false
                        },1000);
                    } else {
                        toastr.error(title+'失败');
                        addFig  =  false
                    }
                });
            }else{
                return;
                addFig  =  false
            }
        };

        function seach() {
            $('#tb_departments').bootstrapTable('refresh');
        }
    </script>
</head>
<body>
<div class="panel-body" style="padding-bottom:0px;">
    <div class="panel panel-default">
        <div class="panel-heading">查询条件</div>
        <div class="panel-body">
            <form id="formSearch" class="form-horizontal">
                <div class="form-group" style="margin-top:15px">
                    <label class="control-label col-sm-1" for="areanumberingc">库位编号</label>
                    <div class="col-sm-3">
                        <input type="text" class="form-control" id="areanumberingc">
                    </div>
                    <label class="control-label col-sm-1" for="areastorehousec">所属仓库</label>
                    <div class="col-sm-3">
                        <select id="areastorehousec" name="areastorehousec" class="form-control select2">
                            <option value="">请选择</option>
                        </select>
                        <span class="xing"></span>
                        <script type="text/javascript">
                            $(function () {
                                $.ajax({
                                    type: "post",
                                    url: "${pageContext.request.contextPath }/base/warehouse/selectAllWarehouse.do",
                                    dataType: 'JSON',
                                    async: false,
                                    success: function (arr) {
                                        var data = [];
                                        for(var i=0;i<arr.length;i++){
                                            data.push({id:arr[i].locationid, text:arr[i].locationname});
                                        }
                                        $('#areastorehousec').select2({
                                            allowClear: true,//清除
                                            //multiple:true,
                                            //tags: true,
                                            //maximumSelectionLength: 1,  //设置最多可以选择多少项
                                            minimumResultsForSearch: -1, //去模糊查询
                                            language: "zh-CN", //设置 提示语言
                                            width: "100%", //设置下拉框的宽度
                                            placeholder: "请选择",
                                            data: data
                                        });
                                        $('#areastorehouse').select2({
                                            allowClear: true,//清除
                                            //multiple:true,
                                            //tags: true,
                                            //maximumSelectionLength: 1,  //设置最多可以选择多少项
                                            minimumResultsForSearch: -1, //去模糊查询
                                            language: "zh-CN", //设置 提示语言
                                            width: "100%", //设置下拉框的宽度
                                            placeholder: "请选择",
                                            data: data
                                        });
                                    }
                                });
                            });

                        </script>
                    </div>
                    <div class="col-sm-4" style="text-align:left;">
                        <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary" onclick="seach()">查询</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default" onclick="doView()">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default" onclick="doDelete()">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
        <%--<button id="btn_add" type="button" class="btn btn-default" onclick="douploadModal()">--%>
            <%--<span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>导入--%>
        <%--</button>--%>
        <%--<button id="btn_delete" type="button" class="btn btn-default" onclick="doExportall()">--%>
            <%--<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出所有--%>
        <%--</button>--%>

        <script type="text/javascript">
            function doExportFile() {
                Ewin.confirm({message : "确认要导出数据模板吗？"}).on(
                    function(e) {
                        if (!e) {return;}
                        window.location.href="${pageContext.request.contextPath}/staff/doExportFile.do";
                    })
            }
            function doExport() {
                Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
                    function(e) {
                        if (!e) {return;}
                        window.location.href="${pageContext.request.contextPath}/staff/doExport.do";
                    })
            }
            function doExportall() {
                Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
                    function(e) {
                        if (!e) {return;}
                        window.location.href="${pageContext.request.contextPath}/staff/doExportall.do";
                    })
            }

            function douploadModal() {
                $('#uploadModal').modal(open);
                //清空表单
                document.getElementById("importForm").reset();
            }

            function uploadBtn() {
                var fileName = $("#fileInput").val();
                if (fileName.length > 0) {
                    var formData = new FormData($("#importForm")[0]);
                    $.ajax({
                        url: '${pageContext.request.contextPath}/staff/uplodeFile.do' ,
                        type: 'post',
                        data: formData,
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            if (data == 1) {
                                toastr.success("文件导入成功！");
                                setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
                                    $('#uploadModal').modal('hide');
                                    $('#tb_departments').bootstrapTable('refresh');
                                },1000);
                            }else if(data == -1){
                                toastr.warning("导入的数据不符合导入条件（员工编号不能重复，找不到对应的部门）！");
                            }else{
                                toastr.warning("文件格式异常，文件导入失败！");
                            }
                        },
                        error: function (data) {
                            toastr.error("文件格式异常，文件导入失败！");
                        }
                    });
                }else{
                    toastr.warning("上传文件为空，请选择要导入的文件！");
                }
            }

        </script>
    </div>
    <table id="tb_departments"></table>
</div>

<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel1">
                    <span>excel导入</span>
                </h4>
            </div>
            <div class="modal-body">
                <div style="text-align:right;padding:5px">
                    <a href="${pageContext.request.contextPath }/datas/tray.xls" onclick="javascript:Preview();">
                        <img alt="导入公司信息-模板" src="${pageContext.request.contextPath }/images/excel_alt_1.png" style="width: 20px;"/>
                        <span style="font-size:larger;font-weight:200;color:red">tray-模板.xls</span>
                    </a>
                </div>
                <form id="importForm" class="form-horizontal">
                    <div title="Excel导入操作" style="padding: 5px">
                        <input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
                    </div>
                </form>
                <!--数据显示表格-->
                <table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0">
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit"  name="submit"  class="btn btn-primary" id="ss" onclick="uploadBtn()">导入</button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content" style="width: 700px;">
            <div class="modal-header">
                <button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel">
                    <span id="bt" style="font-size:13px"></span>
                </h4>
            </div>
            <div class="modal-body">
                <form id="fm" class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">库位编号:</label>
                        <div class="col-sm-7">
                            <input type="text" class="form-control" id="areanumbering" name="areanumbering" placeholder="请输入" autocomplete="off">
                            <input type="hidden" id="positionId" name="positionId" >
                            <span class="xing"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-3 control-label">库位名称:</label>
                        <div class="col-sm-7">
                            <input type="text" class="form-control" id="areaname" name="areaname"  placeholder="请输入" autocomplete="off">
                            <span class="xing"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">所属仓库:</label>
                        <div class="col-sm-7">
                            <select id="areastorehouse" name="areastorehouse" class="form-control select2">
                            </select>
                            <span class="xing"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">库位类型:</label>
                        <div class="col-sm-7">
                            <input type="text" class="form-control" id="areatype" name="areatype"  placeholder="请输入" autocomplete="off">
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default closefm" data-dismiss="modal" >关闭</button>
                        <button type="button"  class="btn btn-primary" onclick="save()">保存</button>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function() {
        $("#fm").bootstrapValidator({
            feedbackIcons : {
                valid : 'glyphicon glyphicon-ok',
                invalid : 'glyphicon glyphicon-remove',
                validating : 'glyphicon glyphicon-refresh'
            },
            fields : {
                areanumbering : {
                    validators : {
                        notEmpty : {
                            message : '库位编号不能为空'
                        },
                    }
                },

                areaname : {
                    validators : {
                        notEmpty : {
                            message : '库位名称不能为空'
                        },
                    }
                },


                areastorehouse : {
                    validators : {
                        notEmpty : {
                            message : '所属仓库不能为空'
                        },
                    }
                }
            },
        });
    });
</script>
</body>
</html>
